<template>
  <div class="device-query-container">
    <!-- 搜索区域修改为两个搜索框 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <!-- 设备ID搜索框 - 确保v-model正确绑定 -->
        <el-input v-model="searchId" placeholder="请输入设备ID搜索" class="search-input"></el-input>
        <!-- 设备名称搜索框 - 确保v-model正确绑定 -->
        <el-input v-model="searchName" placeholder="请输入设备名称搜索" class="search-input"></el-input>
      </div>
      <div class="button-group">
        <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
        <el-button type="default" @click="handleReset" class="reset-button">重置</el-button>
      </div>
    </el-card>

    <!-- 设备表格区域 -->
    <el-card class="card-container table-card">
      <el-table :data="paginatedData" style="width: 100%;" class="custom-table rounded-table"
        :header-cell-style="{ backgroundColor: '#1890ff !important', color: '#fff !important', borderBottom: '2px solid white !important' }"
        row-class-name="table-row">
        <!-- 添加 align="center" 属性使内容居中 -->
        <el-table-column prop="id" label="设备ID" stripe style="width: 30%" align="center"></el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" stripe style="width: 60%" align="center"></el-table-column>
        <el-table-column label="操作" stripe style="width: 10% ; float: right;" align="center">
          <template #default="scope">
            <el-button class="repair-button" size="small" @click="openRepairDialog(scope.row)">报修</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <span class="total-text">总计 {{ total }} 台设备</span>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="prev, pager, next, jumper" :prev-text="'上一页'" :next-text="'下一页'" :jumper="{ text: '前往' }"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 报修悬浮框 -->
    <el-dialog v-model="repairDialogVisible" title="设备故障报修" width="500px" :close-on-click-modal="false">
      <!-- 悬浮框内容保持不变 -->
      <el-form ref="repairFormRef" :model="repairForm" label-width="100px" class="repair-form">
        <!-- 删除设备ID填写框 -->
        <el-form-item label="故障描述" prop="remark" :rules="[{ required: true, message: '请输入故障描述', trigger: 'blur' }]">
          <el-input type="textarea" v-model="repairForm.remark" :rows="5" placeholder="请详细描述设备故障情况"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="repairDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRepair" :loading="submitLoading">
            {{ submitLoading ? '提交中...' : '提交报修' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import { ElButton, ElCard, ElTable, ElTableColumn, ElPagination, ElMessage, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
import request from '@/utils/request';

export default {
  name: 'DeviceQuery',
  components: {
    ElButton,
    ElCard,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput
  },
  setup() {
    // 表格数据相关
    const allDevices = ref([]); // 存储所有设备数据
    const paginatedData = ref([]); // 存储分页后的数据
    // 删除未使用的searchKeyword变量
    // const searchKeyword = ref('');
    const searchId = ref(''); // 设备ID搜索变量
    const searchName = ref(''); // 设备名称搜索变量
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    let refreshTimer = null;

    // 报修对话框相关
    const repairDialogVisible = ref(false);
    const submitLoading = ref(false);
    const currentEquipmentId = ref(null); // 新增：存储当前报修设备ID
    const repairForm = reactive({
      remark: ''
    });

    // 虚拟设备数

    // 获取设备列表数据 - 加入虚拟数据逻辑
    const fetchDevices = async () => {
      try {
        // 尝试从后端获取数据
        const response = await request.get('/equipment/getAllEquipment');

        // 修改状态码判断条件，匹配后端实际返回的200
        if (response.code === 200 && response.data) {
          // 使用后端数据，移除length判断以支持空数据显示
          allDevices.value = response.data;
          ElMessage.success('设备列表获取成功');
        } else {
          // 添加错误状态处理
          allDevices.value = [];
          ElMessage.warning(`获取失败: ${response?.msg || '未知错误'}`);
        }
      } catch (error) {
        // 网络错误时使用虚拟数据
        console.error('设备列表接口调用失败，使用虚拟数据:', error);
        allDevices.value = [...virtualDevices];
        ElMessage.warning('网络异常，已加载本地示例数据');
      }

      // 触发搜索过滤和分页
      handleSearch();
    };

    // 搜索和分页处理 - 纯前端实现
    // 修复搜索逻辑 - 同时处理ID和名称搜索
    const handleSearch = () => {
      let filteredData = [...allDevices.value];

      // 多条件搜索过滤 - 添加设备ID搜索
      if (searchId.value) {
        const idKeyword = searchId.value.toLowerCase();
        filteredData = filteredData.filter(device =>
          device.id.toString().includes(idKeyword)
        );
      }

      if (searchName.value) {
        const nameKeyword = searchName.value.toLowerCase();
        filteredData = filteredData.filter(device =>
          device.equipmentName.toLowerCase().includes(nameKeyword)
        );
      }

      total.value = filteredData.length;
      const startIndex = (currentPage.value - 1) * pageSize.value;
      paginatedData.value = filteredData.slice(startIndex, startIndex + pageSize.value);
    };

    // 分页变化处理
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      handleSearch();
    };

    // 打开报修对话框
    const openRepairDialog = (row) => {
      // 添加类型检查和默认值
      if (!row || !row.id) {
        ElMessage.error('无法获取设备信息');
        return;
      }
      currentEquipmentId.value = Number(row.id); // 确保转换为数字类型
      repairForm.remark = '';
      repairDialogVisible.value = true;
    };

    // 提交报修请求
    const submitRepair = async () => {
      // 添加参数验证
      if (!currentEquipmentId.value || isNaN(currentEquipmentId.value)) {
        ElMessage.error('设备ID无效');
        return;
      }
      if (!repairForm.remark.trim()) {
        ElMessage.error('请输入故障描述');
        return;
      }

      try {
        submitLoading.value = true;
        const response = await request.post('/users/repairRequests', {
          equipmentId: currentEquipmentId.value, // 已确保是数字类型
          remark: repairForm.remark
        });

        // 提交报修请求中的成功处理部分
        if (response.code === 200) {
          // 使用success类型确保绿色提示，并引用后端返回的data字段
          ElMessage.success({
            message: response.data || '提交申请成功',
            type: 'success', // 显式指定success类型确保绿色
            duration: 3000
          });
          repairDialogVisible.value = false;
        } else {
          ElMessage.error(response.msg || '提交失败，请重试');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
        console.error('报修接口调用失败:', error);
      } finally {
        submitLoading.value = false;
      }
    };

    // 设置定时刷新 (每60秒)
    const setupRefreshTimer = () => {
      refreshTimer = setInterval(() => {
        fetchDevices();
      }, 600000); // 修改此处的时间间隔，从5000(5秒)改为60000(60秒)
    };

    // 页面挂载时初始化
    onMounted(() => {
      fetchDevices();
      setupRefreshTimer();

      // 删除监听searchKeyword的代码
      // watch(searchKeyword, () => {
      //   currentPage.value = 1; // 搜索时重置到第一页
      //   handleSearch();
      // });
    });

    // 页面卸载时清理
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
    });

    // 添加重置方法
    const handleReset = () => {
      searchId.value = '';
      searchName.value = '';
      currentPage.value = 1;
      handleSearch();
    };

    return {
      // 删除searchKeyword的返回
      searchId, searchName,
      paginatedData, currentPage, pageSize, total,
      repairDialogVisible, repairForm, submitLoading,
      handleSearch, handleCurrentChange, openRepairDialog, submitRepair,
      handleReset
    };
  }
};
</script>

<style scoped>
/* 添加卡片容器样式 */
.card-container {
  width: 70%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card {
  padding: 20px;
  margin-top: 20px;
}

.table-card {
  padding: 20px;
}

/* 修改分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 调整搜索容器宽度 */
.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}

.search-button,
.reset-button {
  padding: 0 20px;
}

.search-input {
  width: 300px;
}

.total-text {
  margin-right: 15px;
  font-size: 14px;
  color: #606266;
}

/* 移除原有表格行悬浮样式 */
/* 表格行样式 */
::v-deep .el-table .table-row:hover {
  background-color: #1890ff !important;
  color: #fff !important;
  font-size: 15px;
  transition: all 0.3s ease !important;
  transform: scale(1.0025);
  transform-origin: center left;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

/* 表头样式补充 */
::v-deep .el-table__header th {
  border-bottom: 2px solid white !important;
}

/* 确保表格内容区域与表头分隔 */
::v-deep .el-table__body tr:first-child td {
  border-top: none !important;
}

/* 三级保障：加强表头样式穿透 */
::v-deep .custom-table .el-table__header-wrapper .el-table__header {
  background-color: #1890ff !important;
}

::v-deep .custom-table .el-table__header th {
  background-color: #1890ff !important;
  color: #fff !important;
  border-bottom: 2px solid white !important;
}

/* 确保没有其他样式干扰 */
::v-deep .custom-table .el-table__cell {
  background-color: transparent !important;
}

/* 修复表格行高度一致性 */
::v-deep .el-table__row {
  height: auto !important;
}

::v-deep .el-table .cell {
  transition: padding 0.3s ease !important;
}

::v-deep .el-table .table-row:hover .cell {
  padding: 12px 15px !important;
}

/* 表格圆角样式 */
::v-deep .rounded-table {
  border-radius: 12px !important;
  overflow: hidden !important;
  border: none !important;
}

/* 表头圆角 */
::v-deep .rounded-table .el-table__header-wrapper {
  border-radius: 12px 12px 0 0 !important;
  overflow: hidden !important;
}

/* 报修按钮样式 - 白色背景蓝色文字 */
:deep(.repair-button) {
  background-color: white !important;
  color: #1890ff !important;
  border: 1px solid #1890ff !important;
}

/* 按钮 hover 效果 */
:deep(.repair-button:hover) {
  background-color: #f5f5f5 !important;
}

/* 确保输入框没有被禁用或遮挡 */
:deep(.el-input__wrapper) {
  pointer-events: auto !important;
  /* 确保可以点击输入 */
  z-index: 1;
  /* 确保输入框在最上层 */
}

/* 添加新的表格行悬浮样式 */
/* 表格行悬浮效果 - 与UserQuery.vue统一 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row {
  transition: all 0.2s ease;
  position: relative;
}

::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
  transform: scale(1.01);
  transform-origin: center left;
  background-color: #1890ff !important;
  color: #fff !important;
  font-size: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 0 5px;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
  width: 100% !important;
}
</style>